<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品编号管理
 *
 * @icon fa fa-barcode
 * @remark 管理产品编号和图片
 */
class ProductItem extends Backend
{
    /**
     * ProductItem模型对象
     * @var \app\admin\model\scanwork\ProductItem
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\ProductItem;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['allocation.order', 'allocation.model.product', 'allocation.process', 'allocation.user', 'report', 'auditUser'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看产品详情
     */
    public function view($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error('产品编号不存在');
        }
        
        // 获取报工图片
        $reportImages = \app\admin\model\scanwork\ItemReportImage::with(['uploadUser'])
            ->where('item_id', $row->id)
            ->select();
        
        // 获取审核图片
        $auditImages = \app\admin\model\scanwork\ItemAuditImage::with(['uploadUser'])
            ->where('item_id', $row->id)
            ->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('reportImages', $reportImages);
        $this->view->assign('auditImages', $auditImages);
        return $this->view->fetch();
    }

    /**
     * 上传报工图片
     */
    public function uploadReportImage()
    {
        $itemId = $this->request->post('item_id');
        $reportId = $this->request->post('report_id');
        
        if (!$itemId || !$reportId) {
            $this->error('参数错误');
        }
        
        // 检查是否有文件上传
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            $this->error('请选择文件');
        }
        
        try {
            // 使用云存储服务上传
            $cloudService = new \app\common\service\ScanworkCloudService();
            $result = $cloudService->uploadReportImage($_FILES['file']);
            
            if ($result['success']) {
                // 保存图片记录
                $imageData = [
                    'item_id' => $itemId,
                    'report_id' => $reportId,
                    'image_url' => $result['url'],
                    'cloud_file_id' => $result['file_id'],
                    'upload_user_id' => $this->auth->id,
                    'createtime' => time()
                ];
                
                $result = \app\admin\model\scanwork\ItemReportImage::create($imageData);
                
                if ($result) {
                    return json(['code' => 1, 'msg' => '上传成功', 'url' => $imageData['image_url'], 'id' => $result->id]);
                } else {
                    $this->error('保存失败');
                }
            } else {
                $this->error($result['message']);
            }
        } catch (Exception $e) {
            $this->error('上传失败：' . $e->getMessage());
        }
    }

    /**
     * 上传审核图片
     */
    public function uploadAuditImage()
    {
        $itemId = $this->request->post('item_id');
        $reportId = $this->request->post('report_id');
        $auditStatus = $this->request->post('audit_status', 1);
        $auditReason = $this->request->post('audit_reason', '');
        
        if (!$itemId || !$reportId) {
            $this->error('参数错误');
        }
        
        // 检查是否有文件上传
        if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
            $this->error('请选择文件');
        }
        
        try {
            // 使用云存储服务上传
            $cloudService = new \app\common\service\ScanworkCloudService();
            $result = $cloudService->uploadAuditImage($_FILES['file']);
            
            if ($result['success']) {
                // 保存图片记录
                $imageData = [
                    'item_id' => $itemId,
                    'report_id' => $reportId,
                    'image_url' => $result['url'],
                    'cloud_file_id' => $result['file_id'],
                    'upload_user_id' => $this->auth->id,
                    'audit_status' => $auditStatus,
                    'audit_reason' => $auditReason,
                    'createtime' => time()
                ];
                
                $result = \app\admin\model\scanwork\ItemAuditImage::create($imageData);
                
                if ($result) {
                    return json(['code' => 1, 'msg' => '上传成功', 'url' => $imageData['image_url'], 'id' => $result->id]);
                } else {
                    $this->error('保存失败');
                }
            } else {
                $this->error($result['message']);
            }
        } catch (Exception $e) {
            $this->error('上传失败：' . $e->getMessage());
        }
    }

    /**
     * 删除报工图片
     */
    public function deleteReportImage($id)
    {
        $img = \app\admin\model\scanwork\ItemReportImage::find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        @unlink(ROOT_PATH . 'public' . $img->image_url);
        $img->delete();
        $this->success('图片已删除');
    }

    /**
     * 删除审核图片
     */
    public function deleteAuditImage($id)
    {
        $img = \app\admin\model\scanwork\ItemAuditImage::find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        
        @unlink(ROOT_PATH . 'public' . $img->image_url);
        $img->delete();
        $this->success('审核图片已删除');
    }

    /**
     * 批量审核产品
     */
    public function batchAudit()
    {
        $itemIds = $this->request->post('item_ids');
        $auditStatus = $this->request->post('audit_status');
        $auditReason = $this->request->post('audit_reason', '');
        
        if (!$itemIds || !in_array($auditStatus, ['1', '2'])) {
            $this->error('参数错误');
        }
        
        $itemIdsArr = is_array($itemIds) ? $itemIds : explode(',', $itemIds);
        
        Db::startTrans();
        try {
            foreach ($itemIdsArr as $itemId) {
                $item = $this->model->find($itemId);
                if ($item) {
                    $item->status = 2; // 已审核
                    $item->audit_user_id = $this->auth->id;
                    $item->audit_time = time();
                    $item->save();
                }
            }
            
            Db::commit();
            $this->success('批量审核成功');
        } catch (Exception $e) {
            Db::rollback();
            $this->error('批量审核失败：' . $e->getMessage());
        }
    }

    /**
     * 获取产品编号列表（用于选择）
     */
    public function getItemList()
    {
        $allocationId = $this->request->get('allocation_id');
        $status = $this->request->get('status', 0);
        
        if (!$allocationId) {
            $this->error('参数错误');
        }
        
        $list = $this->model
            ->where('allocation_id', $allocationId)
            ->where('status', $status)
            ->field('id, item_no, status')
            ->select();
        
        $this->success('', null, $list);
    }
} 